﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
using System;

public class XLuaBehaviour : MonoBehaviour {

	public string LuaPath;

	private Action luaStart;
	private Action luaUpdate;
	private Action luaOnDestroy;

	private LuaTable scriptEnv;

	void Awake()
	{
		BinaryObject bo = ResourceManager.Instance.GetResource (LuaPath + ".txt", typeof(TextAsset), enResourceType.Lua).m_content as BinaryObject;
		if (bo == null) {
			return;
		}

		scriptEnv = LuaManager.luaEnv.NewTable();

		LuaTable meta = LuaManager.luaEnv.NewTable();
		meta.Set("__index", LuaManager.luaEnv.Global);
		scriptEnv.SetMetaTable(meta);
		meta.Dispose();

		scriptEnv.Set("self", this);

		LuaManager.luaEnv.DoString(bo.m_data, gameObject.name, scriptEnv);

		Action luaAwake = scriptEnv.Get<Action>("awake");
		scriptEnv.Get("start", out luaStart);
		scriptEnv.Get("update", out luaUpdate);
		scriptEnv.Get("ondestroy", out luaOnDestroy);

		if (luaAwake != null)
		{
			luaAwake();
		}
	}

	// Use this for initialization
	void Start ()
	{
		if (luaStart != null)
		{
			luaStart();
		}
	}

	// Update is called once per frame
	void Update ()
	{
		if (luaUpdate != null)
		{
			luaUpdate();
		}
	}

	void OnDestroy()
	{
		if (luaOnDestroy != null)
		{
			luaOnDestroy();
		}
		luaOnDestroy = null;
		luaUpdate = null;
		luaStart = null;
		if (scriptEnv != null) {
			scriptEnv.Dispose ();
		}
	}
}
